#include "main.h"
#include "uninstall.h"
#include "ui_uninstall.h"
#include "uninstallthread.h"
#include "uninstallintroduce.h"

uninstall::uninstall(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::uninstall)
{
    ui->setupUi(this);

    this->setWindowIcon(QIcon(":/xin.ico"));
    this->setWindowTitle(tr("%1 %2 卸载").arg(xin::exeName).arg(xin::versions));
    ui->textEdit->setReadOnly(true);
    ui->textEdit->setCursor(QCursor(Qt::CursorShape::ArrowCursor));

}

void uninstall::init()
{
    //读取注册表
    QString uninstallPath;
    QSettings settingsUninstall("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + xin::exeName,
                                QSettings::NativeFormat);
    if (settingsUninstall.contains("InstallLocation")) {
        uninstallPath = settingsUninstall.value("InstallLocation").toString();
    }
    else {
        QMessageBox msgBox;
        msgBox.setText(tr("安装路径获取失败,请手动删除!"));
        msgBox.exec();
        exit(0);
    }

    QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的卸载").arg(xin::exeName).arg(xin::versions) ,
                                       tr("你确定要完全卸载%1 %2, 及其所有组件?").arg(xin::exeName).arg(xin::versions),
                                       QMessageBox::Yes | QMessageBox::No);

    box->button(QMessageBox::Yes)->setText(tr("是(Y)"));
    box->button(QMessageBox::Yes)->setShortcut(Qt::Key_Y);
    box->button(QMessageBox::No)->setText(tr("否(N)"));
    box->button(QMessageBox::No)->setShortcut(Qt::Key_N);
    box->button(QMessageBox::No)->setFocus(); //设置焦点
    //此move会有变动
    box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
    int ret = box->exec();
    if (ret == QMessageBox::Yes) {
        if (uninstallPath.isEmpty()) {
            QMessageBox msgBox;
            msgBox.setText(tr("安装路径获取失败,请手动删除!"));
            msgBox.exec();
            exit(0);
        }
        if (!QFileInfo(uninstallPath).exists()) {
            QMessageBox msgBox;
            msgBox.setText(("安装路径不存在,请手动删除!"));
            msgBox.exec();
            exit(0);
        }
        //获取文件数量
        files = getFiles(uninstallPath);

        uninstallThread* unthread = new uninstallThread(files);
        connect(this, SIGNAL(signalRemove(QString)), unthread, SLOT(removeFile(QString)));
        connect(unthread, SIGNAL(signalUpdate(double)), this, SLOT(updateWidget(double)));
        connect(unthread, SIGNAL(signalError(QString)), this, SLOT(onError(QString)));
        QThread* Thread = new QThread();
        unthread->moveToThread(Thread);
        Thread->start();

        if (!files.isEmpty()) { //把文件夹全部插在最前面
            for (int i = 0; i < files.size(); ++i) {
                if (QFileInfo(files.at(i)).isDir()) {
                    QString dirPath = files.at(i);
                    files.removeAt(i);
                    files.push_front(dirPath);
                }
            }
            files.push_front(uninstallPath);

            emit signalRemove(files.last());
            files.removeLast();
        }
    }
    else {
        exit(0);
    }
}

QStringList uninstall::getFiles(QString path)
{
    if (!path.endsWith('/')) {
        path.append('/');
    }
    QDir dir(path);
    QStringList files;

    foreach (QString name, dir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
        QString newPath = path + name;
        if (!QFileInfo(newPath).isSymLink() && QFileInfo(newPath).isDir()) {
            files.append(getFiles(newPath));
        }
        qDebug() << QFileInfo(newPath).size();
        files.append(newPath);
    }

    return files;
}

void uninstall::delRegedit()
{
    QSettings settingsUninstall("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\",
                                QSettings::NativeFormat);
    settingsUninstall.remove(xin::exeName);

    QSettings settingsXiaoXin("HKEY_CLASSES_ROOT\\", QSettings::NativeFormat);
    settingsXiaoXin.remove(xin::exeName);
    settingsXiaoXin.remove(xin::exeName + "Versions");
}

void uninstall::updateWidget(double data)
{
    ui->progressBar->setValue(data);
    if (!files.isEmpty()) {
        ui->labelProgress->setText(tr("删除文件: ") + files.last() + "..."
                                   + QString("%1%").arg((int)data));
        ui->textEdit->append(tr("删除文件: ") + files.last() + "...");
        emit signalRemove(files.last()); //返给线程
        files.removeLast();
    }
    else {
        ui->progressBar->setValue(100);
        ui->textEdit->append(tr("%1 %2 已成功完成卸载!").arg(xin::exeName).arg(xin::versions));
        delRegedit(); //删除注册表
        this->hide();
        QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的卸载").arg(xin::exeName).arg(xin::versions) ,
                                           tr("%1 %2 已成功地从您的计算机移除.").arg(xin::exeName).arg(xin::versions),
                                           QMessageBox::Yes);

        box->button(QMessageBox::Yes)->setText(tr("确定"));

        box->button(QMessageBox::Yes)->setFocus(); //设置焦点
        //删除卸载程序
        QFile(previousUnExePath).remove();

        //此move会有变动
        box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
        int ret = box->exec();
        if (ret == QMessageBox::Yes) {
            exit(0);
        }
    }
}

void uninstall::onError(QString error)
{
    QMessageBox msgBox;
    msgBox.setText(error);
    msgBox.exec();
    exit(0);
}

int entry(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //待更新Linux版


    if (argc >= 3) {
        previousUnExePath = argv[1];
        QString temp = argv[2];
        if (temp == "key") {
            QSharedMemory shared;
            shared.setKey("UNXin");
            if (shared.attach()) {
                QMessageBox msgBox;
                msgBox.setText("已有一个安装程序启动,请勿重复启动");
                msgBox.exec();
                exit(0);
            }
            shared.create(1);


            QTranslator translator;
            qDebug() <<  translator.load(":/resourceFile/Chinese.qm");
            a.installTranslator(&translator);


            UninstallIntroduce* unInstall = new UninstallIntroduce();
            unInstall->show();
        }
    }

    //windows 临时存储路径
    QString homeTempPath = QDir::tempPath() + "/";
    QString currentPath = QCoreApplication::applicationFilePath();
    QProcess* pro = new QProcess();
    if (QDir(homeTempPath).exists()) {
        homeTempPath = homeTempPath + QCoreApplication::applicationName() + ".exe";
        if (QFileInfo(homeTempPath).exists()) {
            QFile(homeTempPath).remove();
        }
        if ((QFile().copy(currentPath, homeTempPath))) {
            pro->start(homeTempPath, QStringList() << currentPath << "key");
            exit(0);
        }
    }
    else {
        QString existsPath;
        for (int i = 0; i < homeTempPath.size(); ++i) { //从头遍历，检测此路径是否在本地存在，只要有一个存在即可安装
            if (QFileInfo(homeTempPath.left(homeTempPath.size() - i)).exists()) {
                existsPath = homeTempPath.left(homeTempPath.size() - i); // 保存存在的路径
                break;
            }
        }
        homeTempPath = homeTempPath + QCoreApplication::applicationName() + ".exe";
        if (QFileInfo(homeTempPath).exists()) {
            QFile(homeTempPath).remove();
        }
        if ((QFile().copy(currentPath, homeTempPath))) {
            pro->start(homeTempPath, QStringList() << currentPath << "key");
            exit(0);
        }
    }

    return a.exec();
}
